package com.ruoyi.business.thread;

import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.business.service.IBRepaymentService;
import com.ruoyi.business.service.impl.BRepaymentServiceImpl;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class TransferToUsThread extends Thread{

    private String threadName;
    private RedisCache redisCache;
    private IBRepaymentService bRepaymentServiceImpl;

    public TransferToUsThread(String threadName, RedisCache redisCache, BRepaymentServiceImpl bRepaymentServiceImpl) {
        this.threadName= threadName;
        this.redisCache = redisCache;
        this.bRepaymentServiceImpl = bRepaymentServiceImpl;
    }

    public void run() {

        String redisName = BizConstants.TRANSFER_TO_US_THREAD+threadName;
        String threadName1 = BizConstants.TRANSFER_TO_US_THREAD_NAME+threadName;

        //设置线程名称
        Thread.currentThread().setName(threadName1);

        //保存进redis
        redisCache.setCacheObject(redisName,threadName1);
        redisCache.expire(redisName,185, TimeUnit.MINUTES);

        String cacheObject = redisCache.getCacheObject(redisName);

        //如果有缓存一直轮询
        while (cacheObject!=null && !StringUtils.isBlank(cacheObject)){

            //查到了新纪录久停止轮询
            if(bRepaymentServiceImpl.getAllReservedAccountOrder(threadName)){
                //休息十分钟
                try{
                    log.error(threadName1+"线程准备睡眠");
                    Thread.sleep(1000*60*10);
                }catch (Exception e){
                    log.error("ussd线程睡眠异常");
                }
                cacheObject = redisCache.getCacheObject(redisName);
            }else{
                //删除缓存
                redisCache.deleteObject(redisName);
                log.info(redisName+"Redis移除");
                cacheObject = null;
            }
        }
        log.info(threadName1+"线程终止");

    }
}
